<template>
    <view class="coupon_list_page">
        <view class="head_nav" v-if="tabList.length > 1">
            <view class="head_content" @click="checkIndex(item.code)" v-for="item in tabList" :key="item.code">
                <view :class="navCode == item.code ? 'activite' : 'common'"
                    >{{ item.name }}<span v-if="item.num && item.code == 0">（{{ item.num }}）</span>
                </view>
                <view class="head_line" v-if="navCode == item.code"></view>
            </view>
        </view>
        <view class="coupon_list">
            <view v-for="item in listData" :key="item.id">
                <view @click="jumpDetail(item, 0)" :class="navCode == 0 ? 'coupon_item' : 'coupon_item coupon_invalid'">
                    <view class="coupon_item_sign">
                        <img :src="getImgFun(item)" />
                    </view>
                    <img v-if="navCode == 1" class="coupon_item_used" :src="getImgOssUrl('/ui-prod-2.13.0/used.png')" />
                    <img
                        v-if="navCode == 2"
                        class="coupon_item_used"
                        :src="getImgOssUrl('/ui-prod-2.13.0/expire.png')" />
                    <view class="coupon_item_container">
                        <view
                            class="coupon_item_left"
                            :style="{
                                'font-size': item.priceFontSize ? item.priceFontSize + 'px' : ''
                            }"
                            >{{ floatDivide(item.customerCouponDiscountContent, 100)
                            }}<text class="unit" v-if="item.couponType === 1">元</text>
                            <text class="unit" v-if="item.couponType === 2">折</text>
                        </view>
                        <view class="coupon_item_right">
                            <view class="coupon_item_title">
                                {{ item.customerCouponTitle }}
                            </view>
                            <view class="coupon_item_condition">
                                <text>{{ conditionContent(item) }}</text>
                                <text v-if="item.couponMatch === 1">全部商品可用</text>
                                <text v-else>部分商品可用</text>
                            </view>
                            <view class="coupon_item_time">
                                用券时间：{{ item.couponTimeStart }}~{{ item.couponTimeEnd }}
                            </view>
                        </view>
                    </view>
                    <view class="coupon_item_action" v-if="navCode == 0">
                        <view class="coupon_item_btn_use btn" @click.stop="jumpDetail(item, 1)">立即使用</view>
                        <view class="coupon_item_btn_read btn">查看详情</view>
                    </view>
                </view>
            </view>
            <view v-if="!listData.length" class="none">
                <img class="empty" :src="getImgOssUrl('/ui-prod-2.0.0/empty_coupon_2.0.png')" alt="" />
                <view class="title">没有{{ tabList.find(x => x.code == navCode).name }}的优惠券</view>
            </view>
            <view v-if="totalCount && totalCount >= capacity && totalCount >= listData.length" class="no_more">
                已经到底啦！
            </view>
            <view class="holder"></view>
            <Loading />
        </view>
    </view>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onReachBottom } from '@dcloudio/uni-app';
import Loading from '@/components/el-loading';
import { getImgOssUrl, floatDivide } from '@/commons/utils';
import router from '@/router';
import request from '@/request';
import storage from '@/commons/storage';

const para = reactive({
    pageSize: 10,
    pageNum: 1
});
const totalCount = ref(0);
const listData = reactive([]);
// 页面可视优惠券数量
const capacity = ref(5);
const navCode = ref(0);

const tabList = reactive([
    { name: '未使用', code: 0, num: '0', value: 1 },
    { name: '已使用', code: 1, num: '', value: 2 },
    { name: '已过期', code: 2, num: '', value: 3 }
]);

const checkIndex = index => {
    navCode.value = index;
    uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
    });
    queryWindowSize();
    initCouponList();
};

const getImgFun = item => {
    let url = '';
    if (item.couponType === 1) {
        url = getImgOssUrl(`/ui-prod-2.13.0/manjian_coupon${navCode.value ? '_used' : '_app'}.png`);
    } else if (item.couponType === 2) {
        url = getImgOssUrl(`/ui-prod-2.13.0/zhekou_coupon${navCode.value ? '_used' : '_app'}.png`);
    }
    return url;
};

const conditionContent = val => {
    switch (val.couponPrerequisites) {
        case 1:
            return '无门槛，';
        case 2:
            return `满${floatDivide(val.couponPrerequisitesAdditional, 100)}元，`;
        case 3:
            return `满${val.couponPrerequisitesAdditional}件，`;
        default:
            return '';
    }
};

const initCouponList = () => {
    listData.length = 0;
    totalCount.value = 0;
    para.pageNum = 1;
    getCouponList();
};

const getCouponList = async () => {
    const res = await request(
        'myCouponListServ',
        Object.assign({ customerCouponStatus: tabList.find(x => x.code == navCode.value).value }, para)
    );
    totalCount.value = res.data.totalCount;
    if (navCode.value == 0) {
        tabList.find(x => x.code == navCode.value).num = totalCount.value;
    }
    if (res.data.list?.length && totalCount.value > listData.length) {
        res.data.list.map(x => {
            const e = Object.assign({}, x, {
                priceFontSize: compareDescLength(x.customerCouponDiscountContent),
                customerCouponOriginId: x.customerCouponOriginId,
                couponType: x.customerCouponType,
                couponDiscountMost: x.customerCouponDiscountMost || 0,
                couponTitle: x.customerCouponTitle,
                couponTimeStart: (x.customerCouponExpireTimeStart || ' ').split(' ')[0].replaceAll('-', '.'),
                couponTimeEnd: (x.customerCouponExpireTimeEnd || ' ').split(' ')[0].replaceAll('-', '.'),
                couponMatch: x.customerCouponMatch,
                couponPrerequisites: x.customerCouponPrerequisites,
                couponPrerequisitesAdditional: x.customerCouponPrerequisitesAdditional
            });
            listData.push(e);
        });
    }
};
// 上拉加载
onReachBottom(() => {
    if (totalCount.value > listData.length) {
        para.pageNum++;
        getCouponList();
    }
});

// val: 0-查看详情，1-立即使用
const jumpDetail = (item, val) => {
    const url = val ? '/pages-user/coupon/use/index' : '/pages-user/coupon/detail/index';
    router.push({
        path: url,
        query: {
            couponId: val ? item.customerCouponOriginId : item.id,
            userCouponStatus: navCode.value
        }
    });
};
const compareDescLength = value => {
    // 可通纳宽度，单位：rpx
    const middleContentwidth = 170 - 25;
    const needNum = String(floatDivide(value, 100)).length;
    if (needNum > 4) {
        //  3个数字约占2个汉字大小，小数点当一个数字算
        const autosize = Math.floor(middleContentwidth / needNum) * 1.5;
        return autosize / storage.get('pixelRatio');
    }
    return '';
};

const checkDescLength = () => {
    if (storage.get('pixelRatio')) {
    } else {
        uni.getSystemInfo({
            success: res => {
                // 得到页面可用高度rpx
                const scale = 750 / res.windowWidth;
                storage.set('pixelRatio', scale);
            }
        });
    }
};

// 计算手机屏幕可见多少优惠券
const queryWindowSize = () => {
    uni.getSystemInfo({
        success: res => {
            // 得到页面可用高度rpx
            const currenntWinHeight = res.windowHeight / (res.windowWidth / 750);
            // 最大容纳量向上取整
            if (navCode.value == 0) {
                capacity.value = Math.ceil((currenntWinHeight - 29 - 85) / (185 + 96 + 29));
            } else {
                capacity.value = Math.ceil((currenntWinHeight - 29 - 85) / (185 + 29));
            }
        }
    });
};

onMounted(async () => {
    checkDescLength();
    queryWindowSize();
    initCouponList();
});
</script>
<style lang="scss" src="./style.scss" scoped></style>
